package com.mvvm.demo.ui.login

import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.mvvm.base.base.view.activity.BaseActivity
import com.mvvm.base.ext.observe
import com.mvvm.base.util.CountDownTimerUtils
import com.mvvm.demo.R
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.kodein.di.Kodein
import org.kodein.di.generic.instance
import kotlin.coroutines.CoroutineContext

class LoginActivity : BaseActivity(), CoroutineScope {
    override val layoutId: Int
        get() = R.layout.activity_login
    override val kodein: Kodein = Kodein.lazy {
        extend(parentKodein)
        import(loginKodeinModule)
    }
    private val viewModel: LoginViewModel by instance<LoginViewModel>()
    private val repo: LoginRepository by instance<LoginRepository>()
    lateinit var countDownTimerUtils:CountDownTimerUtils
    override fun initView(savedInstanceState: Bundle?) {
        launch {
            var userInfo = repo.queryUserInfo()
            if (userInfo!=null){
                ARouter.getInstance().build("/app/detail/").navigation()
                finish()
            }else{
                binds()
            }
        }
    }

    private fun binds() {
        get_code_tv.setOnClickListener {
            viewModel.getVerficationCode(tvUsername.text.toString())
             countDownTimerUtils = CountDownTimerUtils(get_code_tv, 60000, 1000)
            countDownTimerUtils.start()
        }

        btn.setOnClickListener {
            viewModel.login(
                    tvUsername.text.toString(),
                    tvPassword.text.toString()
            )
        }


        observe(viewModel.stateLiveData, this::onNewState)
    }


    private fun onNewState(state: LoginViewState) {


        if (state.userInfo != null) {
            countDownTimerUtils.cancel()
            ARouter.getInstance().build("/app/detail/").navigation()
            finish()
        } else if (!TextUtils.isEmpty(state.error)) {
            com.mvvm.base.util.toast { state.error!! }
        }
    }

    companion object {
        private const val TAG = "LoginFragment"
    }

    private var job: Job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    }

}